package com.du.ichat;

import android.accessibilityservice.AccessibilityService;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.JsonReader;
import android.util.JsonWriter;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.du.ichat.adapter.MessageAdapter;
import com.du.ichat.bean.TestMessage;
import com.du.ichat.fragment.EmojiFragment;
import com.du.ichat.listener.SoftKeyBoardListener;
import com.du.ichat.utils.BaseActivity;
import com.du.ichat.utils.EmojiStringUtils;
import com.du.ichat.utils.MessageCreater;
import com.du.ichat.utils.UserManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.QueryDirectionEnum;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import junit.framework.Test;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatActivity extends BaseActivity {
    private EditText etMessage;
    private ImageButton btnVoice,btnImage , btnMore;
    private Button btnSend;
    private RecyclerView recyclerView;
    private List<IMMessage> datas = new ArrayList<>();
    private MessageAdapter adapter;
    private NimUserInfo friend;
    private TextView tvTitle;
    private ImageButton btnBack;
    private NimUserInfo userinfo;
    private LoginInfo loginInfo;
    private LinearLayoutManager layoutManager;
    private ViewPager emojiViewPager;
    private List<String> emojiNames;
    private View emojiLayout;
    private ImageButton btnText;
    private InputMethodManager imm;
    private boolean isKeyboardShow;
    private boolean isShowSendBtn = false;
    private EmojiClickListenerImpl emojiClickListener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(new IncomingMessageObserver(), true);
        initData();
        initView();



    }



    class IncomingMessageObserver implements Observer<List<IMMessage>> {

        @Override
        public void onEvent(List<IMMessage> imMessages) {
            adapter.addDatas(imMessages);
            scrollToBottom();
        }
    }

    private void initData() {
        emojiNames = new ArrayList<>();
        try {

            JsonReader reader = new JsonReader(new InputStreamReader(getAssets().open("order.json")));
            reader.beginArray();
            while(reader.hasNext()){
                emojiNames.add(reader.nextString());
            }
            reader.endArray();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        emojiClickListener = new EmojiClickListenerImpl();
        userinfo = UserManager.getUserinfo(this);
        loginInfo = UserManager.getLoginInfo(this);
        friend = (NimUserInfo) getIntent().getSerializableExtra("friendInfo");
        IMMessage message = MessageBuilder.createEmptyMessage(friend.getAccount() , SessionTypeEnum.P2P , System.currentTimeMillis());
        NIMClient.getService(MsgService.class).queryMessageListEx(message, QueryDirectionEnum.QUERY_OLD,
                20, false).setCallback(new RequestCallback<List<IMMessage>>() {
            @Override
            public void onSuccess(List<IMMessage> imMessages) {
                Collections.reverse(imMessages);
                datas.addAll(imMessages);
                initView();
            }

            @Override
            public void onFailed(int i) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }

    private void initView() {

        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        btnText = findViewById(R.id.chat_text_btn);
        emojiLayout = findViewById(R.id.emojiLayout);
        emojiViewPager = findViewById(R.id.emojiViewPager);
        tvTitle = findViewById(R.id.tvTitle);
        recyclerView = findViewById(R.id.chatRecyclerVeiw);
        etMessage = findViewById(R.id.chat_messge_et);
        btnSend = findViewById(R.id.chat_btn_send);
        btnVoice = findViewById(R.id.chat_voice_btn);
        btnImage = findViewById(R.id.chat_img_btn);
        btnMore = findViewById(R.id.chat_more_btn);
        btnBack = findViewById(R.id.back);
        tvTitle.setText(friend.getName());
        adapter = new MessageAdapter(friend , userinfo );
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter.setDatas(datas);
        recyclerView.setAdapter(adapter);
        scrollToBottom();
        emojiViewPagerAdapter adapter = new emojiViewPagerAdapter(getSupportFragmentManager());
        emojiViewPager.setAdapter(adapter);
        etMessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(TextUtils.isEmpty(charSequence)){
//                    btnMore.setVisibility(View.VISIBLE);
//                    btnSend.setVisibility(View.GONE);
                    showSendBtn(false);
                }else{
                    showSendBtn(true);
//                    btnMore.setVisibility(View.INVISIBLE);
//                    btnSend.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        btnVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                log("voice click");
            }
        });
        btnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        btnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                emojiLayout.setVisibility(View.VISIBLE);
                showEmojiLayout();
                btnImage.setVisibility(View.INVISIBLE);
                btnText.setVisibility(View.VISIBLE);
                imm.hideSoftInputFromWindow(etMessage.getWindowToken(), 0);
            }
        });
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendMessage();
            }
        });
        btnText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                emojiLayout.setVisibility(View.GONE);
                btnImage.setVisibility(View.VISIBLE);
                btnText.setVisibility(View.GONE);
            }
        });
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                log("recyclerview click");
                emojiLayout.setVisibility(View.GONE);
                btnImage.setVisibility(View.VISIBLE);
                btnText.setVisibility(View.GONE);
                return false;
            }
        });

        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                isKeyboardShow = true;
                emojiLayout.setVisibility(View.GONE);
                hideEmojiLayout();
                btnImage.setVisibility(View.VISIBLE);
                btnText.setVisibility(View.GONE);
            }

            @Override
            public void keyBoardHide(int height) {
                isKeyboardShow = false;
//                if(btnText.getVisibility() == View.VISIBLE){
//                    btnText.setVisibility(View.GONE);
//                    btnImage.setVisibility(View.VISIBLE);
//                    emojiLayout.setVisibility(View.VISIBLE);
//                }
            }
        });
    }

    private void sendMessage() {
        String text = etMessage.getText().toString();
        IMMessage message = MessageCreater.getP2PTestMessage(friend.getAccount() , text);
        NIMClient.getService(MsgService.class).sendMessage(message, false);
        adapter.addItem(message);
        etMessage.setText("");
        scrollToBottom();
    }

    private void scrollToBottom(){
        recyclerView.smoothScrollToPosition(adapter.getItemCount());
    }

    class emojiViewPagerAdapter extends FragmentPagerAdapter{



        public emojiViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            EmojiFragment emojiFragment = new EmojiFragment();
            Bundle bundle = new Bundle();
            ArrayList<String> temp = new ArrayList<>();
            temp.addAll(emojiNames.subList(21 * position,(position +1 ) * 21));
            bundle.putStringArrayList("emojis" , temp);
            emojiFragment.setArguments(bundle);
            emojiFragment.setEmojiItemClickListener(emojiClickListener);
            return emojiFragment;
        }

        @Override
        public int getCount() {
            return 4;
        }
    }


    private void showEmojiLayout(){
        ObjectAnimator anim = ObjectAnimator.ofFloat(emojiLayout, "translationY",  emojiLayout.getHeight(), 0f);
        anim.setDuration(50);
        anim.start();
    }

    private void hideEmojiLayout(){
        ObjectAnimator anim = ObjectAnimator.ofFloat(emojiLayout, "translationY",  0f, emojiLayout.getHeight());
        anim.setDuration(50);
        anim.start();
        emojiLayout.setVisibility(View.GONE);
    }


    class EmojiClickListenerImpl implements EmojiFragment.OnEmojiItemClickListener{

        @Override
        public void onEmojiClick(String emojiName) {
            log(emojiName);
            String message = etMessage.getText().toString()  + getString(R.string.emojiString , emojiName);
            log(message);
            SpannableString newMessage = EmojiStringUtils.getEmojiString(ChatActivity.this , message);
            etMessage.setText(newMessage);
            etMessage.setSelection(newMessage.length());
        }
    }

    private void showSendBtn(boolean show){
        if(show){
            btnMore.setVisibility(View.INVISIBLE);
            btnSend.setVisibility(View.VISIBLE);
        }else {
            btnMore.setVisibility(View.VISIBLE);
            btnSend.setVisibility(View.GONE);
        }
    }


}
